package com.sailing.xjpb.elasticsearch.util;

import com.google.common.collect.Lists;
import com.sailing.xjpb.common.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.commons.lang3.time.DateUtils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author luozy
 * createTime 2020/5/23
 */
@Slf4j
public class EsUtil {
    public static final String FORMART_YYYY_MM_DD_HH_MM_SS = "yyyy-MM-dd HH:mm:ss";
    public static final String FORMART_YYYY_MM_DD = "yyyy-MM-dd";

    public static final String TYPE = "doc";
    public static final List<String> TYPES = Arrays.asList("doc");

    /**
     * @param beginTime:开始时间
     * @param endTime:       结束时间
     * @param pattern:       日期格式化格式
     * @param indexPrefix:   数据文件前缀 索引名
     * @return: java.util.List<java.lang.String>
     * @author 罗志银
     * createDate 2020/08/10 11:37
     * editUser罗志银
     * editDate 2020/08/10 11:37
     */
    public static List<String> getIndexs(String beginTime, String endTime, String pattern, String indexPrefix) {
        indexPrefix = indexPrefix + "_";
        List<String> indexs = Lists.newArrayList();
        if (StringUtils.isBlank(beginTime) && StringUtils.isBlank(endTime)) {
            indexs.add(indexPrefix + "*");
            return indexs;
        }
        if (StringUtils.isBlank(beginTime)) {
            beginTime = dateToStr(new Date());
        }
        if (StringUtils.isBlank(endTime)) {
            endTime = dateToStr(new Date());
        }

        String datePattern = "yyyy-MM-dd";

        LinkedList<String> tempIndexs = Lists.newLinkedList();
        try {
            int between = daysBetween(parseDate(beginTime, pattern), parseDate(endTime, pattern));

            if (between == 0) {
                StringBuffer sb = new StringBuffer(indexPrefix);
                sb.append(DateFormatUtils.format(parseDate(beginTime, pattern), datePattern));
                indexs.add(sb.toString());
                return indexs;
            }

            tempIndexs.add(DateFormatUtils.format(DateUtils.addDays(parseDate(beginTime, pattern), -1),
                    datePattern));
            for (int i = 0; i <= between; i++) {
                tempIndexs.addLast(DateFormatUtils.format(DateUtils.addDays(parseDate(beginTime, pattern), i),
                        datePattern));
            }
            tempIndexs.add(DateFormatUtils
                    .format(DateUtils.addDays(parseDate(beginTime, pattern), between + 1), datePattern));
            char[] firstIndexChar = tempIndexs.getFirst().toCharArray();
            char[] lastIndexChar = tempIndexs.getLast().toCharArray();
            StringBuffer sb = new StringBuffer(indexPrefix);
            if (firstIndexChar.length == lastIndexChar.length) {
                for (int i = 0; i <= firstIndexChar.length; i++) {
                    char a = firstIndexChar[i];
                    char b = lastIndexChar[i];
                    if (a == b) {
                        sb.append(a);
                    } else {
                        break;
                    }
                }
            }
            indexs.add(sb.append("*").toString());
        } catch (Exception e) {
            log.warn("根据时间段查询符合条件的索引index={}过程中出现错误：{}~{}", indexPrefix, beginTime, endTime);
            log.warn("根据时间段查询符合条件的索引过程中出现错误！", e);
            return Arrays.asList(indexPrefix + "*");
        }
        return indexs;
    }

    /**
     * @param beginTime: 开始时间
     * @param endTime:   结束时间 * @return: int 计算2个时间之间相差几天
     * @author 罗志银
     * createDate 2020/08/10 12:27
     * editUser罗志银
     * editDate 2020/08/10 12:27
     */
    public static int daysBetween(Date beginTime, Date endTime) {
        Calendar beginDateCalender = Calendar.getInstance();
        beginDateCalender.setTime(beginTime);

        Calendar endDateCalender = Calendar.getInstance();
        endDateCalender.setTime(endTime);

        double beginLong = beginDateCalender.getTimeInMillis();
        double endLong = endDateCalender.getTimeInMillis();
        double divisor = (double) 1000 * 3600 * 24;
        double betweenDays = (endLong - beginLong) / divisor;
        return (int) Math.ceil(betweenDays);
    }

    /**
     * @param date: 时间 时间格式化
     * @return: java.lang.String
     * @author 罗志银
     * createDate 2020/08/10 12:29
     * editUser罗志银
     * editDate 2020/08/10 12:29
     */
    public static String dateToStr(Date date) {
        return dateToStr(date, "yyyy-MM-dd HH:mm:ss");
    }

    /**
     * @param date:       时间
     * @param formateStr: 格式化格式 时间转字符串
     * @return: java.lang.String
     * @author 罗志银
     * createDate 2020/08/10 12:30
     * editUser罗志银
     * editDate 2020/08/10 12:30
     */
    public static String dateToStr(Date date, String formateStr) {
        if (date == null) {
            return "";
        }
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(formateStr);
        return simpleDateFormat.format(date);
    }


    public static Date parseDate(String dateStr, String formateStr) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(formateStr);
        try {
            return simpleDateFormat.parse(dateStr);
        } catch (ParseException e) {
            throw BusinessException.businessError("请检查时间是否正确：{}", e);
        }
    }

}
